#include <iostream>
#include <windows.h>

CRITICAL_SECTION cs1, cs2;

void DeadlockThread1(int threadId)
{
    EnterCriticalSection(&cs1);
    std::cout << "Thread " << threadId << " entered cs1\n";
    Sleep(100); // 让线程暂停一段时间，以便另一个线程有机会执行
    EnterCriticalSection(&cs2);
    std::cout << "Thread " << threadId << " entered cs2\n";
    LeaveCriticalSection(&cs2);
    LeaveCriticalSection(&cs1);
}

void DeadlockThread2(int threadId)
{
    EnterCriticalSection(&cs2);
    std::cout << "Thread " << threadId << " entered cs2\n";
    Sleep(100); // 让线程暂停一段时间，以便另一个线程有机会执行
    EnterCriticalSection(&cs1);
    std::cout << "Thread " << threadId << " entered cs1\n";
    LeaveCriticalSection(&cs1);
    LeaveCriticalSection(&cs2);
}

int main()
{
    InitializeCriticalSection(&cs1);
    InitializeCriticalSection(&cs2);

    HANDLE thread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DeadlockThread1, (LPVOID)1, 0, NULL);
    HANDLE thread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DeadlockThread2, (LPVOID)2, 0, NULL);

    WaitForSingleObject(thread1, INFINITE);
    WaitForSingleObject(thread2, INFINITE);

    DeleteCriticalSection(&cs1);
    DeleteCriticalSection(&cs2);

    return 0;
}